<template>
  <a-modal v-model:visible="isShow" title="关联人员" :width="'900px'" :body-style="{ width: '900px', height: '550px' }">
    <div class="role-manage-transfer-page">
      <a-transfer
        v-model:target-keys="targetKeys"
        :data-source="mockData"
        :disabled="disabled"
        :show-search="showSearch"
        :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
        :show-select-all="false"
        :row-key="(record) => record.code"
        @change="onChange"
      >
        <template
          #children="{ direction, filteredItems, selectedKeys, disabled: listDisabled, onItemSelectAll, onItemSelect }"
        >
          <div>
            <div style="margin: 5px 10px">
              <a-input-search v-if="direction === 'left'" placeholder="搜索" @search="onSearch"></a-input-search>
            </div>
            <a-table
              v-if="direction === 'left'"
              :row-selection="{
                selectedRowKeys: getRowSelectionL.selectedRowKeys,
                onChange: (selectedRowKeys) =>
                  getRowSelectionL.onSelectChange(selectedRowKeys, onItemSelectAll, onItemSelect),
              }"
              :columns="direction === 'left' ? leftColumns : rightColumns"
              :data-source="filteredItems"
              size="small"
              :style="{ pointerEvents: listDisabled ? 'none' : null }"
              :custom-row="
                ({ key, disabled: itemDisabled }) => ({
                  onClick: () => {
                    if (itemDisabled || listDisabled) return
                    onItemSelect(key, !selectedKeys.includes(key))
                  },
                })
              "
              :scroll="{ y: 346 }"
              :pagination="direction === 'left' ? paginfoL : false"
              @change="
                (pagination) => {
                  direction === 'left' ? onChangeTableL(pagination, onItemSelectAll) : () => {}
                }
              "
            />
            <a-table
              v-else
              :row-selection="
                getRowSelection({
                  disabled: listDisabled,
                  selectedKeys,
                  onItemSelectAll,
                  onItemSelect,
                })
              "
              :columns="direction === 'left' ? leftColumns : rightColumns"
              :data-source="filteredItems"
              size="small"
              :style="{ pointerEvents: listDisabled ? 'none' : null }"
              :custom-row="
                ({ key, disabled: itemDisabled }) => ({
                  onClick: () => {
                    if (itemDisabled || listDisabled) return
                    onItemSelect(key, !selectedKeys.includes(key))
                  },
                })
              "
              :scroll="{ y: 346 }"
              :pagination="direction === 'left' ? paginfoL : false"
              @change="
                (pagination) => {
                  direction === 'left' ? onChangeTableL(pagination) : () => {}
                }
              "
            />
          </div>
        </template>
      </a-transfer>
    </div>
    <template #footer>
      <a-button type="primary" @click="getUserBind">确定</a-button>
      <a-button @click="cancal">取消</a-button>
    </template>
  </a-modal>
</template>
<script>
import { defineComponent, ref, inject, reactive } from 'vue'
import factory from '../factory'

export default defineComponent({
  emits: ['update-bind', 'close'],
  setup(_, ctx) {
    const { currentItemId } = inject('roleParams')
    //==定义数据===================================
    const mockData = ref([])
    const leftTableColumns = [
      {
        dataIndex: 'code',
        title: '工号',
      },
      {
        dataIndex: 'name',
        title: '姓名',
      },
      {
        dataIndex: 'mobile',
        title: '手机号',
      },
    ]
    const rightTableColumns = leftTableColumns

    //==穿梭框方法===========================================
    const targetKeys = ref([])
    const disabled = ref(false)
    const showSearch = ref(false)
    const leftColumns = ref(leftTableColumns)
    const rightColumns = ref(rightTableColumns)
    const onChange = (nextTargetKeys) => {
      console.log('nextTargetKeys', nextTargetKeys)
      let arr = mockData.value.filter((m) => nextTargetKeys.includes(m.code))
      if (rightArr.length > arr.length) {
        //减员
      } else {
        //增员
        rightArr = [...rightArr, ...arr]
      }
      rightArr = arr
    }
    //==人员绑定===
    const getUserBind = () => {
      let post = { users: targetKeys.value, role: currentItemId.value.key }
      factory.getUserBind(post).then((res) => {
        ctx.emit('update-bind', '')
        cancal()
      })
    }
    const getRowSelection = ({ disabled, selectedKeys, onItemSelectAll, onItemSelect }) => {
      if (onItemSelect.name === 'onLeftItemSelect') {
      } else if (onItemSelect.name === 'onRightItemSelect') {
      }
      return {
        getCheckboxProps: (item) => ({
          disabled: disabled || item.disabled,
        }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows.filter((item) => !item.disabled).map(({ key }) => key)
          onItemSelectAll(treeSelectedKeys, selected)
        },
        onSelect({ key }, selected) {
          onItemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys,
      }
    }
    const getRowSelectionL = reactive({
      selectedRowKeys: [],
      onSelectChange: (selectedRowKeys, onItemSelectAll, onItemSelect) => {
        console.log('selectedRowKeys changed: ', selectedRowKeys)
        getRowSelectionL.selectedRowKeys = selectedRowKeys
        //选中时,重写穿梭框选中项, onItemSelectAll 是穿梭框的方法
        onItemSelectAll([], false)
        onItemSelectAll(selectedRowKeys, true)
      },
    })

    //==翻页功能======================
    const paginfoL = reactive({ pageNo: 1, pageSize: 10, total: 10, search: '' })
    const onChangeTableL = (pagination, onItemSelectAll) => {
      getRowSelectionL.selectedRowKeys = [] //翻页时,清空选中项
      onItemSelectAll([], false) //翻页时,清空穿梭框选中项
      paginfoL.pageNo = pagination.current
      paginfoL.pageSize = pagination.pageSize
      getUserToBound(paginfoL)
    }
    const onChangeTableR = (pagination) => {
      debugger
    }

    //==显示============================================
    const isShow = ref(false)
    const changeVisible = () => {
      isShow.value = true
    }
    const cancal = () => {
      isShow.value = false
      ctx.emit('close', '')
    }

    //==得到人员待绑定=============================
    let rightArr = [] //保存已经选中的员工
    const getUserToBound = (paginfo) => {
      factory.getUserToBound(paginfo).then((res) => {
        mockData.value = [...res.data.dataList, ...rightArr]
        paginfoL.total = res.data.pageCount
      })
    }
    getUserToBound(paginfoL)

    //==搜索===============
    const onSearch = (val) => {
      paginfoL.search = val
      paginfoL.pageNo = 1
      getUserToBound(paginfoL)
    }

    return {
      mockData,
      targetKeys,
      disabled,
      showSearch,
      leftColumns,
      rightColumns,
      onChange,
      getRowSelection,
      isShow,
      changeVisible,
      onChangeTableL,
      onChangeTableR,
      getUserBind,
      cancal,
      onSearch,
      paginfoL,
      getRowSelectionL,
    }
  },
})
</script>

<style lang="less">
.role-manage-transfer-page {
  .ant-pagination-options {
    display: none;
  }
}
</style>
